const fs = require('fs');
const path = require('path');

// 确保日志目录存在
const logDir = path.join(__dirname, '../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 日志级别
const LEVELS = {
  ERROR: 'error',
  WARN: 'warn',
  INFO: 'info',
  DEBUG: 'debug'
};

class Logger {
  constructor() {
    // 为每个级别创建独立的日志文件
    this.logFiles = {
      error: path.join(logDir, 'error.log'),
      warn: path.join(logDir, 'warn.log'),
      info: path.join(logDir, 'info.log'),
      debug: path.join(logDir, 'debug.log')
    };
  }

  /**
   * 记录日志
   * @param {string} level 日志级别
   * @param {string} message 日志消息
   * @param {object} meta 元数据
   */
  log(level, message, meta = {}) {
    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      level,
      message,
      ...meta
    };

    const logString = JSON.stringify(logEntry) + '\n';
    
    // 根据日志级别写入对应的文件
    const logFile = this.logFiles[level];
    if (logFile) {
      fs.appendFileSync(logFile, logString);
    }
    
    // 在开发环境中也输出到控制台
    if (process.env.NODE_ENV !== 'production') {
      console.log(`[${timestamp}] ${level.toUpperCase()}: ${message}`, meta);
    }
  }

  error(message, meta) {
    this.log(LEVELS.ERROR, message, meta);
  }

  warn(message, meta) {
    this.log(LEVELS.WARN, message, meta);
  }

  info(message, meta) {
    this.log(LEVELS.INFO, message, meta);
  }

  debug(message, meta) {
    this.log(LEVELS.DEBUG, message, meta);
  }
}

module.exports = new Logger();